package com.esd.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.esd.common.pojo.PageResult;
import com.esd.common.pojo.R;
import com.esd.device.entity.*;
import com.esd.device.entity.dto.DeviceChannelDto;
import com.esd.device.entity.dto.DeviceDto;
import com.esd.device.entity.dto.DeviceExcel;
import com.esd.device.entity.vo.*;
import com.esd.device.mapper.*;
import com.esd.device.service.DeviceService;
import com.esd.device.task.DeviceConstants;
import com.github.liaochong.myexcel.core.DefaultExcelReader;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("deviceService")
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Autowired
    private LineMapper lineMapper ;

    @Override
    public R selectDevicePage(Map<String,Object> params) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        if (params.get("deviceType") != null ) {
            System.out.println(params.get("deviceType"));
            queryWrapper.eq(Device::getDeviceType, params.get("deviceType"));
        }
        if (params.get("stationId") != null && !params.get("stationId").toString().trim().isEmpty()) {
            queryWrapper.like(Device::getStationId, params.get("stationId").toString().trim());
        }
        if (params.get("lineId") != null) {
            queryWrapper.eq(Device::getLineId, params.get("lineId"));
        }
        if (params.get("position")!=null && !params.get("position").toString().isEmpty()) {
            queryWrapper.like(Device::getPosition, params.get("position").toString());
        }
        Page<Device> devicePage = this.page(
                new Page<>((Integer)params.get("currentPage"), (Integer)params.get("pageSize")), queryWrapper);
        List<DeviceVo> deviceVos = new ArrayList<>();
        for (Device device : devicePage.getRecords()) {
            DeviceVo deviceVo = new DeviceVo();
            deviceVo.setDeviceId(device.getDeviceId());
            deviceVo.setDeviceTypeName(device.getDeviceType());
            deviceVo.setStationId(device.getStationId());
            deviceVo.setViewEnabled(device.getViewEnabled());
            Line line = lineMapper.selectById(device.getLineId());
            deviceVo.setLine(line.getLineName());
            deviceVo.setSignalChannel(device.getSignalChannel());
            deviceVo.setPosition(device.getPosition());
            Gateway gateway = gatewayMapper.selectById(device.getGatewayId());
            deviceVo.setGatewayId(gateway.getGatewayId());
            deviceVo.setServerIp(gateway.getServerIp());
            deviceVo.setServerPort(gateway.getServerPort());
            // 终端的通道列表
            deviceVo.setChannelTypes(deviceChannelMapper.getListByDeviceId(device.getDeviceId()));
            deviceVos.add(deviceVo);
        }

        return R.ok(new PageResult(devicePage.getTotal(), deviceVos));
    }

    @Autowired
    private GatewayMapper gatewayMapper ;

    @Autowired
    private DeviceMapper deviceMapper ;

    @Transactional
    @Override
    public R addDevice(DeviceDto deviceDto) {
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,  device);
        if (selectByStationID(device.getStationId()) != null)
            return R.error("该终端编号已存在！请通过编号查找编辑！！");

        Integer NO = baseMapper.getLatestNo() ;
        if (NO == null) {
            NO = 0;
        }
        device.setDno( NO + 1);
        baseMapper.insert(device); // 数据库id自增的情况下id会自动回显

        if (deviceDto.getChannelTypes() != null && !deviceDto.getChannelTypes().isEmpty()){
            for (int i = 0; i < deviceDto.getChannelTypes().size(); i++) {
                DeviceChannel deviceChannel = getDeviceChannel(deviceDto, i, device);
                deviceChannelMapper.insert(deviceChannel);
            }
        }
        return R.ok("添加终端成功！！");
    }

    private static DeviceChannel getDeviceChannel(DeviceDto deviceDto, int i, Device device) {
        DeviceChannelDto deviceChannelDto = deviceDto.getChannelTypes().get(i);
        DeviceChannel deviceChannel = new DeviceChannel();
        deviceChannel.setDeviceId(device.getDeviceId());
        deviceChannel.setChannelType(deviceChannelDto.getChannelType());
        deviceChannel.setEnabled(deviceChannelDto.getEnabled());
        deviceChannel.setLineId(deviceDto.getLineId());
        deviceChannel.setStationId(deviceDto.getStationId());
        if (deviceChannelDto.getPosition() == null || deviceChannelDto.getPosition().trim().isEmpty()) {
            deviceChannel.setPosition(deviceDto.getPosition() + "_" + ( i + 1 ));
        } else {
            deviceChannel.setPosition(deviceChannelDto.getPosition());
        }
        deviceChannel.setChannel(i + 1);
        deviceChannel.setDeviceType(deviceDto.getDeviceType());
        return deviceChannel;
    }

    @Autowired
    private EsdLogMapper esdLogMapper ;

    @Transactional
    @Override
    public R updateDevice(DeviceDto deviceDto) {
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,  device);
        Device device1 = selectByStationID(deviceDto.getStationId());
        Device device2 = baseMapper.selectById(deviceDto.getDeviceId());
        if ( device1 != null && !device.getDeviceId().equals(device1.getDeviceId()))
            return R.error("该终端编号已存在！请通过编号查找编辑！！");

        baseMapper.updateById(device);

        LambdaQueryWrapper<DeviceChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceChannel::getDeviceId, deviceDto.getDeviceId());
        deviceChannelMapper.delete(queryWrapper);

        if (deviceDto.getChannelTypes() != null && !deviceDto.getChannelTypes().isEmpty()) {
            for (int i = 0; i < deviceDto.getChannelTypes().size(); i++) {
                DeviceChannel deviceChannel = getDeviceChannel(deviceDto, i, device);
                deviceChannelMapper.insert(deviceChannel);
            }
        }
        if (!deviceDto.getStationId().equals(device2.getStationId())){
            int count = countChannels(deviceDto.getDeviceId());
            for (int j = 1; j <= count; j++) {
                DeviceConstants.ChannelStatusMap.remove(device2.getStationId() + "_" + j);
            }
            LambdaQueryWrapper<EsdLog> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.like(EsdLog::getStationId ,  device2.getStationId() + "_%");
            queryWrapper1.eq(EsdLog::getStatus , "失联") ;
            esdLogMapper.delete(queryWrapper1);
        }

        return R.ok("终端信息修改成功！！");
    }

    // 要修改的。。。 （应该是终端的vo）
    @Override
    public Device selectByStationID(String stationID) {
        LambdaQueryWrapper<Device> query = new LambdaQueryWrapper<>();
        query.eq(Device::getStationId, stationID);
        return baseMapper.selectOne(query,false);
    }

    @Transactional
    @Override
    public R uploadDeviceData(MultipartFile file) throws IOException {
        List<DeviceExcel> result = DefaultExcelReader.of(DeviceExcel.class)
                .sheet(0) // 0代表第一个，如果为0，可省略该操作，也可sheet("名称")读取
                .rowFilter(row -> row.getRowNum() > 0) // 如无需过滤，可省略该操作，0代表第一行
                .startSheet(sheet -> {})
                .read(file.getInputStream());// 可接收inputStream

        // 终端已经存在的话，就修改记录
        for (DeviceExcel deviceExcel : result){

            if ( deviceExcel.getDeviceTypeName() == null
                 || deviceExcel.getStationId() == null
                    || deviceExcel.getLineName() == null
                    || deviceExcel.getSignalChannel() == null
                    || deviceExcel.getServerIp() == null
                    || deviceExcel.getPosition() == null
                    || deviceExcel.getChannels() == null
            ){
                continue;
            }
            Device device = new Device();
            LambdaQueryWrapper<Line> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(Line::getLineName, deviceExcel.getLineName());
            Line line = lineMapper.selectOne(queryWrapper3,false);
            device.setLineId(line.getLineId());
            device.setStationId(deviceExcel.getStationId());
            device.setPosition(deviceExcel.getPosition());
            device.setDeviceType(deviceExcel.getDeviceTypeName());
            device.setSignalChannel(deviceExcel.getSignalChannel());

            LambdaQueryWrapper<Gateway> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Gateway::getSignalChannel, deviceExcel.getSignalChannel());
            queryWrapper.eq(Gateway::getServerIp, deviceExcel.getServerIp());
            Gateway gateway = gatewayMapper.selectOne(queryWrapper ,false);
            device.setGatewayId(gateway.getGatewayId());
            Device device1 = selectByStationID(deviceExcel.getStationId());
            if (device1 != null) {
                device.setDeviceId(device1.getDeviceId());
                // 终端已经存在的话，就修改记录
                baseMapper.updateById(device);

                LambdaQueryWrapper<EsdLog> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.like(EsdLog::getStationId ,  device1.getStationId() + "_%");
                queryWrapper1.eq(EsdLog::getStatus , "失联") ;
                esdLogMapper.delete(queryWrapper1);
            }else {
                baseMapper.insert(device);
            }
            // 处理终端的通道信息
            if (deviceExcel.getChannels()!=null && !deviceExcel.getChannels().trim().isEmpty()) {
                String[] ss = deviceExcel.getChannels().split("，"); // 中文逗号
                // 先删除再添加
                LambdaQueryWrapper<DeviceChannel> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(DeviceChannel::getDeviceId, device.getDeviceId());
                deviceChannelMapper.delete(queryWrapper2);

                for (String s : ss) {
                    DeviceChannel deviceChannel = new DeviceChannel();
                    deviceChannel.setDeviceId(device.getDeviceId());
                    deviceChannel.setChannelType(s);
                    deviceChannel.setEnabled(true);
                    deviceChannelMapper.insert(deviceChannel);
                }

            }
        }
        return R.ok("数据上传导入成功！！");
    }

    @Autowired
    private DeviceChannelMapper deviceChannelMapper ;

    @Transactional
    @Override
    public R deleteDevice(Long deviceId) {
        int count = countChannels(deviceId);
        LambdaQueryWrapper<DeviceChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceChannel::getDeviceId, deviceId);
        deviceChannelMapper.delete(queryWrapper);
        Device device = baseMapper.selectById(deviceId);
        for (int i = 0; i < count; i++) {
            DeviceConstants.ChannelStatusMap.remove(device.getStationId() + "_" + (i+1)) ;
        }
        baseMapper.deleteById(deviceId);
        LambdaQueryWrapper<EsdLog> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.like(EsdLog::getStationId ,  device.getStationId() + "_%");
        queryWrapper1.eq(EsdLog::getStatus , "失联") ;
        esdLogMapper.delete(queryWrapper1);
        return R.ok("删除终端成功！！");
    }

    // 根据产线查询终端列表。需要修改 （应该是终端的vo列表）
    @Override
    public R selectByLine(Long lineId) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getLineId, lineId);
        List<Device> devices = baseMapper.selectList(queryWrapper);
        return R.ok(devices);
    }

    @Transactional
    @Override
    public R batchDelete(List<Long> ids) {
        for (Long id : ids) {
            int count = countChannels(id);
            Device device = baseMapper.selectById(id);
            for (int i = 0; i < count; i++) {
                DeviceConstants.ChannelStatusMap.remove(device.getStationId() + "_" + (i+1)) ;
            }
            LambdaQueryWrapper<EsdLog> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.like(EsdLog::getStationId ,  device.getStationId() + "_%");
            queryWrapper1.eq(EsdLog::getStatus , "失联") ;
            esdLogMapper.delete(queryWrapper1);
        }

        for (Long id : ids) {
            baseMapper.deleteById(id);
            LambdaQueryWrapper<DeviceChannel> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DeviceChannel::getDeviceId, id);
            deviceChannelMapper.delete(queryWrapper);
        }
        return R.ok("多条终端信息删除成功！！");
    }

    @Override
    public DeviceDto selectById(Long deviceId) {
        Device device = getById(deviceId);
        if (device == null) {
            return null;
        }
        DeviceDto deviceDto = new DeviceDto();
        BeanUtils.copyProperties(device, deviceDto);
        LambdaQueryWrapper<DeviceChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeviceChannel::getDeviceId, deviceId);
        List<DeviceChannel> deviceChannels = deviceChannelMapper.selectList(queryWrapper);
        List<DeviceChannelDto> deviceChannelDtos = new ArrayList<>();
        if (deviceChannels != null && !deviceChannels.isEmpty()) {
            deviceChannels.forEach(deviceChannel -> {
                DeviceChannelDto deviceChannelDto = new DeviceChannelDto();
                deviceChannelDto.setChannelType(deviceChannel.getChannelType());
                deviceChannelDto.setEnabled(deviceChannel.getEnabled());
                deviceChannelDto.setPosition(deviceChannel.getPosition());
                deviceChannelDtos.add(deviceChannelDto);
            });
        }
        deviceDto.setChannelTypes(deviceChannelDtos);
        return deviceDto;
    }


    @Override
    public R getByLineAndType(String lineName, String deviceType) {
        List<DeviceVo> list = deviceMapper.getByLineAndType(lineName , deviceType);
        return R.ok(list);
    }

    @Override
    public int countChannels(Long deviceId) {
        return deviceMapper.countChannels(deviceId);
    }

    @Override
    public Map<String, Integer> getCount() {
        Map<String,Integer> resultMap = new HashMap<>();
        Long deviceCount = deviceMapper.selectCount(null);
        Long lineCount = lineMapper.selectCount(null);
        Long channelCount = deviceChannelMapper.selectCount(null);
        resultMap.put("lineCount" , lineCount.intValue());
        resultMap.put("deviceCount" , deviceCount.intValue());
        resultMap.put("channelCount" , channelCount.intValue());
        return resultMap;
    }

    @Override
    public List<DeviceVo> selectVosByServerIp(String serverIp) {
        return deviceMapper.selectVosByServerIp(serverIp);
    }

    @Override
    public R getStatisticsData() {
        HashMap<String, Integer> resultMap = new HashMap<>();
        resultMap.put("total", 0);
        resultMap.put("normal", 0);
        resultMap.put("miss", 0);
        resultMap.put("standBy", 0);
        resultMap.put("error", 0);

        HashMap<String, Integer> errorResultMap = new HashMap<>();
        errorResultMap.put("fan", 0);
        errorResultMap.put("td", 0);
        errorResultMap.put("sh", 0);
        errorResultMap.put("sb", 0);

        List<HashMap<String, Object>> allStationIdAndSignalChannelCount = deviceMapper.getAllStationIdAndSignalChannelCount();
        for (HashMap<String, Object> map : allStationIdAndSignalChannelCount) {
            Long channelCount = (Long) map.get("channelCount");
            String stationId = (String) map.get("stationId");
            for (int i = 1; i <= channelCount.intValue(); i++) {
                if (DeviceConstants.ChannelStatusMap.containsKey(stationId + "_" + i)) {
                    PositionStoreVo positionStoreVo = DeviceConstants.ChannelStatusMap.get(stationId + "_" + i);
                    switch (positionStoreVo.getStatus()) {
                        case "正常":
                            resultMap.put("normal", resultMap.get("normal") + 1);
                            break;
                        case "失联":
                            resultMap.put("miss", resultMap.get("miss") + 1);
                            break;
                        case "待机":
                            resultMap.put("standBy", resultMap.get("standBy") + 1);
                            break;
                        case "异常":
                            switch (positionStoreVo.getChannelTypeName()) {
                                case "ESD手环":
                                    errorResultMap.put("sh", errorResultMap.get("sh") + 1);
                                    break;
                                case "台垫接地":
                                    errorResultMap.put("td", errorResultMap.get("td") + 1);
                                    break;
                                case "设备接地":
                                    errorResultMap.put("sb", errorResultMap.get("sb") + 1);
                                    break;
                                case "离子风扇":
                                    errorResultMap.put("fan", errorResultMap.get("fan") + 1);
                                    break;
                            }
                            resultMap.put("error", resultMap.get("error") + 1);
                            break;
                    }
                } else {
                    resultMap.put("miss", resultMap.get("miss") + 1);
                }
            }
        }
        int total = resultMap.get("normal") + resultMap.get("miss") + resultMap.get("error") + resultMap.get("standBy") ;
        resultMap.put("total" , total ) ;
        Map<String, Object> rt = new HashMap<>();
        rt.put("resultMap", resultMap);
        rt.put("errorResultMap", errorResultMap);
        return R.ok(rt);
    }


    @Override
    public R getUnNormalData() {
        List<HashMap<String, Object>> missList = esdLogMapper.getTop6LogsByStatus("失联");
        List<HashMap<String, Object>> errorList = esdLogMapper.getTop6LogsByStatus("异常");
        List<List<HashMap<String, Object>>> missResult = new ArrayList<>() ;
        List<List<HashMap<String, Object>>> errorResult = new ArrayList<>() ;
        // 数据分行
        int i = 0;
        while (i < missList.size()) {
            List<HashMap<String, Object>> list1;
            if (i + 3 < missList.size()) {
                list1 = missList.subList(i, i + 3);
            } else {
                list1 = missList.subList(i, missList.size());
            }
            missResult.add(list1);
            i = i + 3;
        }

        i = 0;
        while (i < errorList.size()) {
            List<HashMap<String, Object>> list2;
            if (i + 3 < errorList.size()) {
                list2 = errorList.subList(i, i + 3);
            } else {
                list2 = errorList.subList(i, errorList.size());
            }
            errorResult.add(list2);
            i = i + 3;
        }
        HashMap<String , Object> resultMap = new HashMap<>() ;
        resultMap.put("miss" , missResult);
        resultMap.put("error" , errorResult);
        return R.ok(resultMap);
    }

    @Override
    public List<HashMap<String, String>> getSortDeviceList(Long lineId) {
        LambdaQueryWrapper<Device> query = new LambdaQueryWrapper<>() ;
        query.orderByAsc(Device::getDno) ;
        query.eq(Device::getLineId , lineId) ;
        List<Device> devices = baseMapper.selectList(query);
        List<HashMap<String, String>> result = new ArrayList<>() ;
        for (Device device : devices){
            HashMap<String, String> map = new HashMap<>();
            map.put("stationId" , device.getStationId());
            map.put("position" , device.getPosition());
            result.add(map);
        }
        return result;
    }

    @Transactional
    @Override
    public R sortDevice(String stationId1, String stationId2) {
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>() ;
        queryWrapper1.eq(Device::getStationId , stationId1) ;

        LambdaQueryWrapper<Device> queryWrapper2 = new LambdaQueryWrapper<>() ;
        queryWrapper2.eq(Device::getStationId , stationId2) ;

        Device device1 = baseMapper.selectOne(queryWrapper1 , false);
        Device device2 = baseMapper.selectOne(queryWrapper2 , false);
        Integer DNO1 = device1.getDno() ;
        Integer DNO2 = device2.getDno() ;
        device1.setDno(DNO2);
        device2.setDno(DNO1);
        baseMapper.updateById(device1);
        baseMapper.updateById(device2);

        List<HashMap<String, String>> list = getSortDeviceList(device1.getLineId());
        return R.ok(list);
    }

    @Override
    public R enabledMon(Long id, String value) {
        int flag = deviceMapper.enabledMon(id, value);
        if (flag == 1) {
            if (value.equals("0")) {
                LambdaQueryWrapper<EsdLog> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(EsdLog::getDeviceId, id);
                queryWrapper.isNull(EsdLog::getEndTime);
                EsdLog esdLog = new EsdLog();
                esdLog.setEndTime(LocalDateTime.now());
                esdLogMapper.update(esdLog, queryWrapper);
            }
            return R.ok();
        }
        return R.error();
    }

    @Override
    public Boolean getViewOn(String stationId) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getStationId, stationId);
        Device device = deviceMapper.selectOne(queryWrapper, false);
//        Line line = lineMapper.selectById(device.getLineId());
        /*if (!line.getViewOn()){
            return false ;
        }*/
        if (device != null) {
            return device.getViewEnabled();
        } else {
            return true;
        }
    }

    public List<List<DustStatusVo>> getDustRows() {
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getViewEnabled , true) ;
        queryWrapper1.eq(Device::getDeviceType, "尘埃粒子计数器");
        List<Device> devices = deviceMapper.selectList(queryWrapper1);
        List<DustStatusVo> dustStatusVos = new ArrayList<>();
        devices.forEach(device -> {
            String position = device.getPosition();
            DustStatusVo dustStatusVo = DeviceConstants.DustStatusMap.get(device.getStationId());
            if (dustStatusVo == null) {
                dustStatusVo = new DustStatusVo();
                dustStatusVo.setPosition(position);
            }
            dustStatusVos.add(dustStatusVo);
        });
        // 数据分行
        List<List<DustStatusVo>> result = new ArrayList<>();
        int i = 0;
        while (i < dustStatusVos.size()) {
            List<DustStatusVo> list1;
            if (i + 4 < dustStatusVos.size()) {
                list1 = dustStatusVos.subList(i, i + 4);
            } else {
                list1 = dustStatusVos.subList(i, dustStatusVos.size());
            }
            result.add(list1);
            i = i + 4;
        }
        return result;
    }

    @Override
    public R getLinesData(Long[] lineIds) {
        if (lineIds == null || lineIds.length == 0) {
            return null;
        } else {
            List<DeltaLineData> deltaLineDatas = new ArrayList<>();
            for (Long lineId : lineIds) {
                DeltaLineData deltaLineData = getDataByLineId(lineId);
                if (deltaLineData != null) {
                    deltaLineDatas.add(deltaLineData);
                }
            }
            return R.ok(deltaLineDatas);
        }
    }

    private DeltaLineData getDataByLineId(Long lineId) {
        Line line = lineMapper.selectById(lineId);
        if (line != null) {
            DeltaLineData deltaLineData = new DeltaLineData();
            deltaLineData.setLineId(lineId);
            deltaLineData.setLineName(line.getLineName());
            List<List<DeltaChannelData>> rows = new ArrayList<>();
            List<DeltaChannelData> lineData;
            lineData = deviceChannelMapper.getLineData(lineId);
            if (!lineData.isEmpty()) {
                for (DeltaChannelData item : lineData) {
                    PositionStoreVo positionStoreVo =
                            DeviceConstants.ChannelStatusMap.get(item.getStationId() + "_" + item.getChannelNum());
                    if (positionStoreVo != null) {
                        item.setStatus(positionStoreVo.getStatus());
                        item.setDetail(positionStoreVo.getDetail());
                        item.setBalancePower(positionStoreVo.getBalancePower());
                        item.setFdzPower(positionStoreVo.getFdzPower());
                    } else {
                        item.setStatus("失联");
                        item.setDetail("失联");
                        item.setBalancePower("0V");
                        item.setFdzPower("0V");
                    }
                }
                int i = 0;
                while (i < lineData.size()) {
                    List<DeltaChannelData> list1;
                    if (i + 12 < lineData.size()) {
                        list1 = lineData.subList(i, i + 12);
                    } else {
                        list1 = lineData.subList(i, lineData.size());
                    }
                    rows.add(list1);
                    i = i + 12;
                }
                deltaLineData.setRows(rows);
                return deltaLineData;
            }
            return null;
        } else {
            return null;
        }
    }

    @Override
    public R getDeviceVoByDeviceId(Long deviceId) {
        Device device = baseMapper.selectById(deviceId);
        Object principal = SecurityUtils.getSubject().getPrincipal();
        if (principal == null) {
            return R.error("进行操作前，请先进行系统登录！！");
        }
        if (device != null) {
            DeviceVo deviceVo = new DeviceVo();
            deviceVo.setDeviceId(device.getDeviceId());
            deviceVo.setDeviceTypeName(device.getDeviceType());
            deviceVo.setStationId(device.getStationId());
            Line line = lineMapper.selectById(device.getLineId());
            deviceVo.setLine(line.getLineName());
            deviceVo.setSignalChannel(device.getSignalChannel());
            deviceVo.setPosition(device.getPosition());
            Gateway gateway = gatewayMapper.selectById(device.getGatewayId());
            deviceVo.setGatewayId(gateway.getGatewayId());
            deviceVo.setServerIp(gateway.getServerIp());
            deviceVo.setServerPort(gateway.getServerPort());
            deviceVo.setViewEnabled(device.getViewEnabled());
            // 终端的通道列表
            deviceVo.setChannelTypes(deviceChannelMapper.getListByDeviceId(device.getDeviceId()));
            return R.ok(deviceVo);
        } else {
            return R.error("该终端不存在！！");
        }

    }
}
